package com.stefanini.pe.bbva.bp.in.security;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.pe.bbva.utils.Constantes;
import com.stefanini.pe.bbva.bp.in.controller.LoginController;
import com.stefanini.pe.bbva.bp.in.model.LoginModel;
import com.stefanini.pe.bbva.bp.in.to.Cliente;
import com.stefanini.pe.bbva.bp.in.to.NoCliente;
import com.stefanini.pe.bbva.bp.in.to.UsuarioSesion;
import com.stefanini.pe.bbva.bp.in.utils.Util;

@Service
public class AuthorizationService {
	public boolean isSessionUserAndContextValide(){
		FacesContext ctx = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);
		if(session != null){
			session.setAttribute(Constantes.OBJETO_CLIENTE_SESSION,null);
			session.setAttribute(Constantes.OBJETO_NO_CLIENTE_SESSION,null);
		}
		return valideUserSession();
	}
	
	public boolean isSessionClientAndContextValide(){
		boolean flag = valideUserSession();
		if(flag){
			FacesContext ctx = FacesContext.getCurrentInstance();		
			HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);
			Cliente cliente = (Cliente) session.getAttribute(Constantes.OBJETO_CLIENTE_SESSION);
			if(cliente == null){
				Util.redirect("/pages/consultas/ConsultaGeneralCliente.xhtml");
				flag = false;
			}else{
				session.setAttribute(Constantes.OBJETO_NO_CLIENTE_SESSION,null);
			}
		}
		return flag;
	}
	
	public boolean isSessionNoClientAndContextValide(){
		boolean flag = valideUserSession();
		if(flag){
			FacesContext ctx = FacesContext.getCurrentInstance();		
			HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);
			NoCliente noCliente = (NoCliente) session.getAttribute(Constantes.OBJETO_NO_CLIENTE_SESSION);
			if(noCliente == null){
				Util.redirect("/pages/asesoria/consultaGeneralNoCliente.xhtml");
				flag = false;
			}else{
				session.setAttribute(Constantes.OBJETO_CLIENTE_SESSION,null);
			}
		}
		return flag;
	}
	
	private boolean valideUserSession(){
		FacesContext ctx = FacesContext.getCurrentInstance();		
		HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);
		boolean flag = false;
		if(ctx == null || session == null){
			Util.redirect("/login.xhtml");
		}else{
			UsuarioSesion userSession = (UsuarioSesion) session.getAttribute(Constantes.USUARIO_SESSION);
			LoginController loginContr = (LoginController)session.getAttribute("loginController");
			LoginModel loginModel = loginContr.getLoginModel();
			if(userSession == null || (loginModel == null || loginModel.getUsuarioSesion() == null)){
				Util.redirect("/login.xhtml");
			}else{
				flag = true;
			}
		}
		return flag;
	}
}